// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Core.Service;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using SqlSugar;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using Admin.NET.Application.Entity;
using Admin.NET.Core;
using Admin.NET.Core.Model;
using System.Text.Json;
namespace Admin.NET.Application;

/// <summary>
/// 库位表服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public partial class WarePlaceModelService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<WarePlaceModel> _warePlaceModelRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public WarePlaceModelService(SqlSugarRepository<WarePlaceModel> warePlaceModelRep, ISqlSugarClient sqlSugarClient)
    {
        _warePlaceModelRep = warePlaceModelRep;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询库位表 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询库位表")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<WarePlaceModelOutput>> Page(PageWarePlaceModelInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _warePlaceModelRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.WarePlaceCode.Contains(input.Keyword) || u.WarePlaceName.Contains(input.Keyword) || u.ShopName.Contains(input.Keyword) || u.WarePlaceNote.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.WarePlaceCode), u => u.WarePlaceCode.Contains(input.WarePlaceCode.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.WarePlaceName), u => u.WarePlaceName.Contains(input.WarePlaceName.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.ShopName), u => u.ShopName.Contains(input.ShopName.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.WarePlaceNote), u => u.WarePlaceNote.Contains(input.WarePlaceNote.Trim()))
            .WhereIF(input.WarePlaceVolume != null, u => u.WarePlaceVolume == input.WarePlaceVolume)
            .WhereIF(input.UserId != null, u => u.UserId == input.UserId)
            .WhereIF(input.WarehouseId != null, u => u.WarehouseId == input.WarehouseId)
            .WhereIF(input.WarePlaceType.HasValue, u => u.WarePlaceType == input.WarePlaceType)
            .Select<WarePlaceModelOutput>();
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取库位表详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取库位表详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<WarePlaceModel> Detail([FromQuery] QueryByIdWarePlaceModelInput input)
    {
        return await _warePlaceModelRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加库位表 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加库位表")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddWarePlaceModelInput input)
    {
        var entity = input.Adapt<WarePlaceModel>();
        if (await _warePlaceModelRep.IsAnyAsync(u => u.WarePlaceCode != null && u.WarePlaceCode == input.WarePlaceCode)) 
            throw Oops.Oh("库位编码已存在");
        if (await _warePlaceModelRep.IsAnyAsync(u => u.WarePlaceName != null && u.WarePlaceName == input.WarePlaceName)) 
            throw Oops.Oh("库位名称已存在");
        return await _warePlaceModelRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新库位表 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新库位表")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateWarePlaceModelInput input)
    {
        if (await _warePlaceModelRep.IsAnyAsync(u => u.Id != input.Id && u.WarePlaceCode != null && u.WarePlaceCode == input.WarePlaceCode)) 
            throw Oops.Oh("库位编码已存在");
        if (await _warePlaceModelRep.IsAnyAsync(u => u.Id != input.Id && u.WarePlaceName != null && u.WarePlaceName == input.WarePlaceName)) 
            throw Oops.Oh("库位名称已存在");
        var entity = input.Adapt<WarePlaceModel>();
        await _warePlaceModelRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除库位表 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除库位表")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteWarePlaceModelInput input)
    {
        var entity = await _warePlaceModelRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _warePlaceModelRep.FakeDeleteAsync(entity);   //假删除
        //await _warePlaceModelRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除库位表 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除库位表")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteWarePlaceModelInput> input)
    {
        var exp = Expressionable.Create<WarePlaceModel>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _warePlaceModelRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _warePlaceModelRep.FakeDeleteAsync(list);   //假删除
        //return await _warePlaceModelRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 导出库位表记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出库位表记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageWarePlaceModelInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportWarePlaceModelOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "库位表导出记录");
    }
    
    /// <summary>
    /// 下载库位表数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载库位表数据导入模板")]
    [ApiDescriptionSettings(Name = "DownloadTemplate"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportWarePlaceModelOutput>(), "库位表导入模板");
    }
    
    private static readonly object _warePlaceModelImportLock = new object();
    /// <summary>
    /// 导入库位表记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入库位表记录")]
    [ApiDescriptionSettings(Name = "ImportData"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (_warePlaceModelImportLock)
        {
            var stream = ExcelHelper.ImportData<ImportWarePlaceModelInput, WarePlaceModel>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.WarePlaceVolume == null){
                            x.Error = "库位容量不能为空";
                            return false;
                        }
                        if (x.WarePlaceType == null){
                            x.Error = "库位状态不能为空";
                            return false;
                        }
                        return true;
                    }).Adapt<List<WarePlaceModel>>();
                    
                    var storageable = _warePlaceModelRep.Context.Storageable(rows)
                        .SplitError(it => string.IsNullOrWhiteSpace(it.Item.WarePlaceCode), "库位编码不能为空")
                        .SplitError(it => it.Item.WarePlaceCode?.Length > 64, "库位编码长度不能超过64个字符")
                        .SplitError(it => string.IsNullOrWhiteSpace(it.Item.WarePlaceName), "库位名称不能为空")
                        .SplitError(it => it.Item.WarePlaceName?.Length > 128, "库位名称长度不能超过128个字符")
                        .SplitError(it => it.Item.ShopName?.Length > 255, "商品名称长度不能超过255个字符")
                        .SplitError(it => it.Item.WarePlaceNote?.Length > 512, "库位备注长度不能超过512个字符")
                        .WhereColumns(it => new { it.WarePlaceCode, it.WarePlaceName })
                        .SplitInsert(it=> !it.Any())
                        .SplitUpdate(it=> it.Any())
                        .ToStorage();
                    
                    storageable.AsInsertable.ExecuteCommand();// 不存在插入
                    storageable.AsUpdateable.UpdateColumns(it => new
                    {
                        it.WarePlaceCode,
                        it.WarePlaceName,
                        it.WarePlaceVolume,
                        it.UserId,
                        it.WarehouseId,
                        it.WarePlaceType,
                        it.ShopName,
                        it.WarePlaceNote,
                    }).ExecuteCommand();// 存在更新
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
    
    /// <summary>
    /// 获取库位商品列表
    /// </summary>
    [DisplayName("获取库位商品列表")]
    [ApiDescriptionSettings(Name = "GetGoodsList"), HttpGet]
    public async Task<List<WarePlaceGoods>> GetGoodsList([Required] long warePlaceId)
    {
        var warePlace = await _warePlaceModelRep.GetFirstAsync(u => u.Id == warePlaceId);
        if (warePlace == null || string.IsNullOrWhiteSpace(warePlace.ShopName))
        {
            return new List<WarePlaceGoods>();
        }
        
        try
        {
            var options = new JsonSerializerOptions
            {
                Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
                PropertyNameCaseInsensitive = true
            };
            return JsonSerializer.Deserialize<List<WarePlaceGoods>>(warePlace.ShopName, options) ?? new List<WarePlaceGoods>();
        }
        catch
        {
            return new List<WarePlaceGoods>();
        }
    }
    
    /// <summary>
    /// 添加商品到库位
    /// </summary>
    [DisplayName("添加商品到库位")]
    [ApiDescriptionSettings(Name = "AddGoods"), HttpPost, UnitOfWork]
    public async Task AddGoods(AddWarePlaceGoodsInput input)
    {
        var warePlace = await _warePlaceModelRep.GetFirstAsync(u => u.Id == input.WarePlaceId);
        if (warePlace == null) throw Oops.Oh("库位不存在");
        
        // 获取现有商品列表
        List<WarePlaceGoods> goodsList = new List<WarePlaceGoods>();
        if (!string.IsNullOrWhiteSpace(warePlace.ShopName))
        {
            try
            {
                var deserializeOptions = new JsonSerializerOptions
                {
                    Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
                    PropertyNameCaseInsensitive = true
                };
                goodsList = JsonSerializer.Deserialize<List<WarePlaceGoods>>(warePlace.ShopName, deserializeOptions) ?? new List<WarePlaceGoods>();
            }
            catch
            {
                goodsList = new List<WarePlaceGoods>();
            }
        }
        
        // 检查是否已存在该商品
        var existingGoods = goodsList.FirstOrDefault(g => g.GoodsName == input.GoodsName);
        if (existingGoods != null)
        {
            // 累加数量
            existingGoods.Quantity += input.Quantity;
            existingGoods.Amount += input.Amount;
            existingGoods.UnitPrice = existingGoods.Amount / existingGoods.Quantity;
            existingGoods.UpdateTime = DateTime.Now;
        }
        else
        {
            // 添加新商品
            goodsList.Add(new WarePlaceGoods
            {
                GoodsId = input.GoodsId,
                GoodsName = input.GoodsName,
                Quantity = input.Quantity,
                Amount = input.Amount,
                UnitPrice = input.Quantity > 0 ? input.Amount / input.Quantity : 0,
                OrderCode = input.OrderCode,
                OrderDate = DateTime.Now,
                OperationType = 1,
                UpdateTime = DateTime.Now
            });
        }
        
        // 保存 - 确保中文正常显示
        var serializeOptions = new JsonSerializerOptions
        {
            Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
            WriteIndented = false
        };
        warePlace.ShopName = JsonSerializer.Serialize(goodsList, serializeOptions);
        await _warePlaceModelRep.AsUpdateable(warePlace).ExecuteCommandAsync();
    }
    
    /// <summary>
    /// 更新库位商品
    /// </summary>
    [DisplayName("更新库位商品")]
    [ApiDescriptionSettings(Name = "UpdateGoods"), HttpPost, UnitOfWork]
    public async Task UpdateGoods(UpdateWarePlaceGoodsInput input)
    {
        var warePlace = await _warePlaceModelRep.GetFirstAsync(u => u.Id == input.WarePlaceId);
        if (warePlace == null) throw Oops.Oh("库位不存在");
        
        if (string.IsNullOrWhiteSpace(warePlace.ShopName))
        {
            throw Oops.Oh("库位没有商品数据");
        }
        
        // 获取现有商品列表
        List<WarePlaceGoods> goodsList;
        try
        {
            var deserializeOptions = new JsonSerializerOptions
            {
                Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
                PropertyNameCaseInsensitive = true
            };
            goodsList = JsonSerializer.Deserialize<List<WarePlaceGoods>>(warePlace.ShopName, deserializeOptions) ?? new List<WarePlaceGoods>();
        }
        catch
        {
            throw Oops.Oh("商品数据解析失败");
        }
        
        // 查找要更新的商品
        var goods = goodsList.FirstOrDefault(g => g.GoodsId == input.GoodsId);
        if (goods == null) throw Oops.Oh("商品不存在");
        
        // 更新商品信息
        if (input.Quantity.HasValue) goods.Quantity = input.Quantity.Value;
        if (input.Amount.HasValue) goods.Amount = input.Amount.Value;
        if (input.Quantity.HasValue && input.Quantity.Value > 0)
        {
            goods.UnitPrice = goods.Amount / goods.Quantity;
        }
        goods.UpdateTime = DateTime.Now;
        
        // 保存 - 确保中文正常显示
        var serializeOptions = new JsonSerializerOptions
        {
            Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
            WriteIndented = false
        };
        warePlace.ShopName = JsonSerializer.Serialize(goodsList, serializeOptions);
        await _warePlaceModelRep.AsUpdateable(warePlace).ExecuteCommandAsync();
    }
    
    /// <summary>
    /// 删除库位商品
    /// </summary>
    [DisplayName("删除库位商品")]
    [ApiDescriptionSettings(Name = "DeleteGoods"), HttpPost, UnitOfWork]
    public async Task DeleteGoods(DeleteWarePlaceGoodsInput input)
    {
        var warePlace = await _warePlaceModelRep.GetFirstAsync(u => u.Id == input.WarePlaceId);
        if (warePlace == null) throw Oops.Oh("库位不存在");
        
        if (string.IsNullOrWhiteSpace(warePlace.ShopName))
        {
            throw Oops.Oh("库位没有商品数据");
        }
        
        // 获取现有商品列表
        List<WarePlaceGoods> goodsList;
        try
        {
            var deserializeOptions = new JsonSerializerOptions
            {
                Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
                PropertyNameCaseInsensitive = true
            };
            goodsList = JsonSerializer.Deserialize<List<WarePlaceGoods>>(warePlace.ShopName, deserializeOptions) ?? new List<WarePlaceGoods>();
        }
        catch
        {
            throw Oops.Oh("商品数据解析失败");
        }
        
        // 删除商品
        var removed = goodsList.RemoveAll(g => g.GoodsId == input.GoodsId);
        if (removed == 0) throw Oops.Oh("商品不存在");
        
        // 保存 - 确保中文正常显示
        var serializeOptions = new JsonSerializerOptions
        {
            Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
            WriteIndented = false
        };
        warePlace.ShopName = JsonSerializer.Serialize(goodsList, serializeOptions);
        await _warePlaceModelRep.AsUpdateable(warePlace).ExecuteCommandAsync();
    }
    
    /// <summary>
    /// 批量更新库位商品
    /// </summary>
    [DisplayName("批量更新库位商品")]
    [ApiDescriptionSettings(Name = "BatchUpdateGoods"), HttpPost, UnitOfWork]
    public async Task BatchUpdateGoods(BatchUpdateWarePlaceGoodsInput input)
    {
        var warePlace = await _warePlaceModelRep.GetFirstAsync(u => u.Id == input.WarePlaceId);
        if (warePlace == null) throw Oops.Oh("库位不存在");
        
        // 使用新的商品列表 - 确保中文正常显示
        var serializeOptions = new JsonSerializerOptions
        {
            Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
            WriteIndented = false
        };
        warePlace.ShopName = JsonSerializer.Serialize(input.GoodsList, serializeOptions);
        await _warePlaceModelRep.AsUpdateable(warePlace).ExecuteCommandAsync();
    }
}

